#include "commands/push_control.h"
#include "catalog/pg_stat_share_storage.h"
#include "storage/lwlocknames.h"
#include "postgres.h"
#include "utils/relcache.h"
#include "access/tupdesc.h"
#include "access/heapam.h"
#include "utils/snapmgr.h"
#include "utils/timestamp.h"
#include "fmgr.h"
#include "utils/fmgrprotos.h"
#include "catalog/indexing.h"

void UpdateStatShareStorage(int64 vcl) {
	Relation pg_stat_share_storage_rel = NULL;
	/* Insert new record in the pg_stat_share_storage table */
	pg_stat_share_storage_rel = table_open(StatShareStorageRelationId, RowExclusiveLock);
	if (RelationIsValid(pg_stat_share_storage_rel)) {
    	TupleDesc pg_stat_share_storage_dsc = NULL;
    	Datum pg_stat_share_storage_record[Natts_pg_stat_share_storage] = {0};
    	bool pg_stat_share_storage_record_nulls[Natts_pg_stat_share_storage] = {false};
		const char* currentTime = NULL;
		TimestampTz nowTime = GetCurrentTimestamp();
		currentTime = timestamptz_to_str(nowTime);
  		pg_stat_share_storage_record[Anum_pg_stat_share_storage_checkpointtime - 1] = DirectFunctionCall3(timestamptz_in, 
			CStringGetDatum(currentTime), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1));
		pg_stat_share_storage_record[Anum_pg_stat_share_storage_applyvcl - 1] = Int64GetDatum(vcl);
  		HeapTuple new_tuple = NULL;
		pg_stat_share_storage_dsc = RelationGetDescr(pg_stat_share_storage_rel);      		
		new_tuple = heap_form_tuple(pg_stat_share_storage_dsc, pg_stat_share_storage_record, pg_stat_share_storage_record_nulls);
		CatalogTupleInsert(pg_stat_share_storage_rel,new_tuple);
		heap_freetuple(new_tuple);
		table_close(pg_stat_share_storage_rel,NoLock);
	}
}

